import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:nine_grid_view/nine_grid_view.dart';
import 'package:o2oa_all_platform/common/extension/date_extension.dart';
import 'package:o2oa_all_platform/common/extension/string_extension.dart';

import '../../../../common/models/im/index.dart';
import '../../../../common/models/orgs/o2_person.dart';
import '../../../../common/routers/routes.dart';
import '../../../../common/utils/o2_api_manager.dart';
import '../../../../common/values/o2.dart';
import '../../../../common/widgets/o2_stateless_widget.dart';
import 'index.dart';

class ConversationPickerPage extends GetView<ConversationPickerController> {
  const ConversationPickerPage({Key? key}) : super(key: key);

  static Future<dynamic> open() async {
    return await Get.toNamed(O2OARoutes.homeImChatPicker);
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<ConversationPickerController>(
      builder: (_) {
        return Scaffold(
            appBar: AppBar(title: Text("im_chat_conversation_picker_title".tr)),
            body: SafeArea(
                child: Container(
              color: Theme.of(context).scaffoldBackgroundColor,
              child: Padding(padding: const EdgeInsets.only(top: 10), child: Obx(() => Column(children: [
                  searchBar(context),
                  const SizedBox(height: 10),
                  Expanded(
                    flex: 1,
                    child: controller.state.showSearchResult
                        ? searchResultView(context)
                        : conversationListView(),
                  )
                ]))),
            )));
      },
    );
  }
  // 搜索栏
  Widget searchBar(BuildContext context) {
    return Padding(
        padding: const EdgeInsets.only(left: 14, right: 14),
        child: Container(
            height: 36,
            decoration: BoxDecoration(
                color: Theme.of(context).colorScheme.background,
                borderRadius: const BorderRadius.all(Radius.circular(18))),
            alignment: Alignment.centerLeft,
            child: Padding(
              padding: const EdgeInsets.only(left: 10),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  SizedBox(
                    width: 22,
                    height: 22,
                    child: Icon(Icons.search,
                        color: Theme.of(context).colorScheme.primary),
                  ),
                  Expanded(
                      flex: 1,
                      child: Padding(
                          padding: const EdgeInsets.only(left: 10),
                          child: TextField(
                            autofocus: false,
                            controller: controller.searchController,
                            decoration: InputDecoration(
                              isDense: true,
                              border: InputBorder.none,
                              hintText: 'contact_picker_search'.tr,
                              hintStyle: Theme.of(context).textTheme.bodySmall,
                            ),
                            style: Theme.of(context).textTheme.bodyLarge,
                            textInputAction: TextInputAction.search,
                            onChanged: (value) => controller.searchInput(value),
                            // onEditingComplete: controller.search,
                          )))
                ],
              ),
            )));
  }

  Widget searchResultView(BuildContext context) {
    return Obx(() => ListView(
      children: [
           if (controller.state.searchConversationList.length > 0)
            _header('im_chat_conversation_picker_search_type_conv'.tr, context),
          if (controller.state.searchConversationList.length > 0)
            _searchResultConversationListView(context),
          if (controller.state.searchPersonList.length > 0)
            _header('im_chat_conversation_picker_search_type_person'.tr, context),
          if (controller.state.searchPersonList.length > 0)
            _searchPersonListView(context),
      ],
    ));
  }

   // 会话搜索结果列表
  Widget _searchResultConversationListView(BuildContext context) {
    return listBoxView(context, Obx(() {
      final conversationList = controller.state.searchConversationList.toList();
      List<Widget> result = [];
      for (var conversation in conversationList) {
        result.add(conversationItemView(context, conversation));
        result.add(const Divider(height: 1));
      }
      return Column(children: result);
    }));
  }

   // 人员搜索结果列表
  Widget _searchPersonListView(BuildContext context) {
    return listBoxView(context, Obx(() {
      final personList = controller.state.searchPersonList.toList();
      List<Widget> result = [];
      for (var person in personList) {
        result.add(_itemPerson(context, person));
        result.add(const Divider(height: 1));
      }
      if (result.isNotEmpty) {
        result.removeLast();
      }
      return Column(children: result);
    }));
  }
   Widget _itemPerson(BuildContext context, O2Person element) {
    return ListTile(
        onTap: () => controller.tapPerson(element),
        title: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            SizedBox(
              width: 32,
              height: 32,
              child: O2UI.personAvatar(element.distinguishedName!, 16)
            ),
            const SizedBox(width: 10),
            Text(element.name ?? '')
          ],
        ));
  }

   Widget _header(String title, BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(top: 10, bottom: 10, left: 14),
      child: Text(title, style: Theme.of(context).textTheme.bodyLarge),
    );
  }
  Widget listBoxView(BuildContext context, Widget body) {
    return Container(
        width: double.infinity,
        decoration:
            BoxDecoration(color: Theme.of(context).colorScheme.background),
        child: body);
  }

  Widget conversationListView() {
    return Obx(() => ListView.separated(
        itemBuilder: (BuildContext context, int index) {
          IMConversationInfo info = controller.state.conversationList[index];
          return conversationItemView(context, info);
        },
        separatorBuilder: (context, index) {
          return const Divider(
            height: 10,
            color: Colors.transparent,
          );
        },
        itemCount: controller.state.conversationList.length));
  }

  Widget conversationItemView(BuildContext context, IMConversationInfo info) {
    String lastTime = '';
    String subTitle = '';
    if (info.lastMessage != null) {
      var last = info.lastMessage!;
      DateTime? time = DateTime.tryParse(last.createTime ?? "");
      if (time != null) {
        lastTime = time.friendlyTime();
      }
      subTitle = last.toBody()?.conversationBodyString() ?? '';
    }
    return Container(
        decoration: BoxDecoration(
          borderRadius: const BorderRadius.all(Radius.circular(10)),
          color: Theme.of(context).colorScheme.background,
        ),
        child: ListTile(
          leading: O2UI.badgeView(
              (info.unreadNumber ?? 0), conversationAvatar(info)),
          title: Text(
            conversationName(info),
            softWrap: true,
            textAlign: TextAlign.left,
            overflow: TextOverflow.ellipsis,
            maxLines: 1,
            style: Theme.of(context).textTheme.bodyLarge,
          ),
          subtitle: Text(
            subTitle,
            softWrap: true,
            textAlign: TextAlign.left,
            overflow: TextOverflow.ellipsis,
            maxLines: 1,
            style: Theme.of(context).textTheme.bodyMedium,
          ),
          trailing:
              Text(lastTime, style: Theme.of(context).textTheme.bodySmall),
          onTap: () => controller.chooseConversation(info),
        ));
  }

  ///
  /// 头像
  /// 群聊使用多个用户头像拼接
  /// 单聊是对方头像
  ///
  Widget conversationAvatar(IMConversationInfo info) {
    if (info.type == O2.imConversationTypeGroup) {
      if (info.personList != null && info.personList!.isNotEmpty) {
        var count = info.personList?.length ?? 0;
        return SizedBox(
            width: 50,
            height: 50,
            child: NineGridView(
              width: 50,
              height: 50,
              padding: const EdgeInsets.all(5),
              space: 5,
              arcAngle: 60, // qqGp 中间间隙的角度
              type: NineGridType.qqGp, //NineGridType.weChat, NineGridType.weiBo
              itemCount: count,
              itemBuilder: (BuildContext context, int index) {
                var personDn = info.personList![index];
                return O2UI.personNetworkImage(personDn);
              },
            ));
      }
    } else {
      var personDn = info.personList?.firstWhereOrNull((element) =>
          element != O2ApiManager.instance.o2User?.distinguishedName);
      if (personDn != null) {
        return SizedBox(
            width: 50, height: 50, child: O2UI.personAvatar(personDn, 25));
      }
    }
    return const SizedBox(
        width: 50,
        height: 50,
        child: CircleAvatar(
          radius: 25,
          backgroundColor: Colors.white,
          backgroundImage: AssetImage('assets/images/group_default.png'),
        ));
  }

  /// 会话标题
  String conversationName(IMConversationInfo info) {
    // 单聊
    if (info.type == O2.imConversationTypeSingle) {
      var otherParty = info.personList?.firstWhereOrNull((element) =>
          element != O2ApiManager.instance.o2User?.distinguishedName);
      if (otherParty != null && otherParty.isNotEmpty) {
        if (otherParty.contains("@")) {
          return otherParty.o2NameCut();
        }
        return otherParty;
      }
      return "";
    } else {
      return info.title ?? "";
    }
  }
}
